//定位当前城市
//当前城市名称 浙江省杭州市
// console.log(returnCitySN.cname);

$(function () {
    //从缓存中获取数据（在登录成功后会将当前用户和用户令牌放入缓存中）
    const user = JSON.parse(window.sessionStorage.getItem("user"));
    const token = window.sessionStorage.getItem("token");
    if (user == null || token == null) {
        alert("请先登录");
        // window.location.href = "../html/welcome.html";
    }

    //滚动条
    $(".tucaoMainContent").scrollBar({
        barWidth: 5, //滚动条的宽度(这里根据需要写数值即可，不设置是10,即默认10px)
        position: "y", //写“x”代表只出水平滚动条，写“y”表示只出垂直滚动条，写“x,y”则出水平和垂直滚动条（只有在内容超出容器时才出现滚动条）
        wheelDis: 60 //滚轮滚动一次向下或向上滚动的距离，默认是15，可根据需要修改数值
    });
    $(".discuss-list").scrollBar({
        barWidth: 5, //滚动条的宽度(这里根据需要写数值即可，不设置是10,即默认10px)
        position: "y", //写“x”代表只出水平滚动条，写“y”表示只出垂直滚动条，写“x,y”则出水平和垂直滚动条（只有在内容超出容器时才出现滚动条）
        wheelDis: 30 //滚轮滚动一次向下或向上滚动的距离，默认是15，可根据需要修改数值
    });

    //discuss.html ? username=第一次测试 & time=2021-04-19T23:08:29.000+00:00 & place=浙江省杭州市 & tucaoContent=第一次测试
    //解析URI中的数据
    const url = window.location.href;
    if (url.split("?").length > 1) {
        const username = decodeURIComponent(url.split("?")[1].split("&")[0].split("=")[1]);
        const time = decodeURIComponent(url.split("?")[1].split("&")[1].split("=")[1]);
        const place = decodeURIComponent(url.split("?")[1].split("&")[2].split("=")[1]);
        const content = decodeURIComponent(url.split("?")[1].split("&")[3].split("=")[1]);
        const id = decodeURIComponent(url.split("?")[1].split("&")[4].split("=")[1]);
        //给评论界面的吐槽内容赋值
        $("#username").html(username);
        $("#time").html(time);
        $("#place").html(place);
        $("#content").html(content);

        const tucaoOrHeart = decodeURIComponent(url.split("?")[1].split("&")[5].split("=")[1]);
        if (tucaoOrHeart == "tucao") {
            //设置背景图
            $("body").attr("onload", "runTucao();")

            //初始化第一页吐槽评论
            getPageDiscussByTucaoIdAjax(token, id, 1);

            //为发布评论按钮添加点击事件
            $("#addDiscussBtn").click(function () {
                const addDiscuss = new AddTucaoDiscuss(user.userId, id, $("#addDiscussContent").val(), returnCitySN.cname, 1);
                addTucaoDiscussAjax(token, addDiscuss, id);
            });

            $("#discussPageSelect").change(function () {
                getPageDiscussByTucaoIdAjax(token, id, $(this).children('option:selected').val());
            })
        } else if (tucaoOrHeart == "heart") {
            //设置背景图
            $("body").attr("onload", "runHeart();")

            //初始化第一页吐槽评论
            getPageDiscussByHeartIdAjax(token, id, 1);

            //为发布评论按钮添加点击事件
            $("#addDiscussBtn").click(function () {
                const addDiscuss = new AddHeartDiscuss(user.userId, id, $("#addDiscussContent").val(), returnCitySN.cname, 1);
                addHeartDiscussAjax(token, addDiscuss, id);
            });

            $("#discussPageSelect").change(function () {
                getPageDiscussByHeartIdAjax(token, id, $(this).children('option:selected').val());
            })
        } else {

        }
    }

    //关闭页面时调用logout方法，退出当前登录用户
    $(window).unload(function () {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url: "http://localhost:2082/logout?username=" + user.username
        })
    });
});


// 时间格式转换
function renderTime(date) {
    var dateee = new Date(date).toJSON();
    // return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
    return new Date(+new Date(dateee)).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
}

//背景 雨玻璃
function runTucao() {
    var image = document.getElementById('background');
    image.onload = function () {
        var engine = new RainyDay({
            image: this,
            blur: 10,
            opacity: 1
        });
        engine.rain([
            [1, 2, 15000]
        ]);
        engine.rain([
            [3, 3, 0.88],
            [5, 5, 0.9],
            [6, 2, 1]
        ], 100);
    };
    image.crossOrigin = 'anonymous';
    image.src = '../img/bg3.jpg';
}

function runHeart() {
    var image = document.getElementById('background');
    image.onload = function () {
        var engine = new RainyDay({
            image: this,
            blur: 10,
            opacity: 1
        });
        engine.rain([
            [1, 2, 15000]
        ]);
        engine.rain([
            [3, 3, 0.88],
            [5, 5, 0.9],
            [6, 2, 1]
        ], 100);
    };
    image.crossOrigin = 'anonymous';
    image.src = '../img/bg2.jpg';
}

//根据tucaoId 分页获取其相对应的评论数据ajax
function getPageDiscussByTucaoIdAjax(token, tucaoId, current) {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token": token
        },
        url: "http://localhost:2082/tucao-discuss/page?tucaoId=" + tucaoId + "&current=" + current,
        success: function (data, status, xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if (responseToken == "overdue") {
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            } else {
                let result = JSON.stringify(data);
                result = eval("(" + result + ")");
                //操作成功
                if (result.code == 200) {
                    const pageData = result.data;
                    //records：获取到的分页数组数据
                    const records = eval("(" + JSON.stringify(pageData) + ")").records;
                    //total：所有数据的数量
                    const total = eval("(" + JSON.stringify(pageData) + ")").total;
                    //size：每页数据的数量
                    const size = eval("(" + JSON.stringify(pageData) + ")").size;
                    //current：当前页数
                    const current = eval("(" + JSON.stringify(pageData) + ")").current;
                    //总页数
                    const pageNum = eval("(" + JSON.stringify(pageData) + ")").pages;

                    //初始化底部分页框
                    $("#discussPageSelect").empty();
                    for (let i = 0; i < pageNum; i++) {
                        let pageValue = i + 1;
                        if (current === pageValue) {
                            $("#discussPageSelect").append("<option value='" + pageValue + "' selected>" + pageValue + "</option>");
                        } else {
                            $("#discussPageSelect").append("<option value='" + pageValue + "'>" + pageValue + "</option>");
                        }
                    }

                    //先清空数据
                    for (let i = 1; i <= 5; i++) {
                        $("#discussUsername" + i).empty();
                        $("#discussTime" + i).empty();
                        $("#discussPlace" + i).empty();
                        $("#discussId" + i).empty();
                        $("#discussContent" + i).empty();
                    }
                    //再进行赋值
                    let tucaoDiscussNum;
                    if ((total - size * (current - 1)) >= 5) {
                        tucaoDiscussNum = 5;
                    } else if ((total - size * (current - 1)) < 5) {
                        tucaoDiscussNum = total - size * (current - 1);
                        for (let i = tucaoDiscussNum + 1; i <= 5; i++) {
                            //添加不可见样式
                            $("#discuss" + i).attr("style", "display:none");
                        }
                    }
                    for (let i = 1; i <= tucaoDiscussNum; i++) {
                        //移除不可见样式
                        $("#discuss" + i).removeAttr("style");
                        let userId = JSON.stringify(records[i - 1].userId);
                        let discussId = JSON.stringify(records[i - 1].discussId);
                        let content = JSON.stringify(records[i - 1].content);
                        let place = JSON.stringify(records[i - 1].place);
                        let createTime = JSON.stringify(records[i - 1].createTime);

                        $("#discussTime" + i).html(renderTime(createTime.replace(/\"/g, "")));
                        $("#discussPlace" + i).html(place.replace(/\"/g, ""));
                        $("#discussId" + i).html(discussId.replace(/\"/g, ""));
                        $("#discussContent" + i).html(content.replace(/\"/g, ""));

                        const HtmlId = "discussUsername" + i;
                        getUserByIdAjax(token, userId, HtmlId);
                    }

                }
                //操作失败
                else if (result.code == 500) {
                    spop({
                        template: result.msg,
                        position: 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//根据heartId 分页获取其相对应的评论数据ajax
function getPageDiscussByHeartIdAjax(token, heartId, current) {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token": token
        },
        url: "http://localhost:2082/heart-discuss/page?heartId=" + heartId + "&current=" + current,
        success: function (data, status, xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if (responseToken == "overdue") {
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            } else {
                let result = JSON.stringify(data);
                result = eval("(" + result + ")");
                //操作成功
                if (result.code == 200) {
                    const pageData = result.data;
                    //records：获取到的分页数组数据
                    const records = eval("(" + JSON.stringify(pageData) + ")").records;
                    //total：所有数据的数量
                    const total = eval("(" + JSON.stringify(pageData) + ")").total;
                    //size：每页数据的数量
                    const size = eval("(" + JSON.stringify(pageData) + ")").size;
                    //current：当前页数
                    const current = eval("(" + JSON.stringify(pageData) + ")").current;
                    //总页数
                    const pageNum = eval("(" + JSON.stringify(pageData) + ")").pages;

                    //初始化底部分页框
                    $("#discussPageSelect").empty();
                    for (let i = 0; i < pageNum; i++) {
                        let pageValue = i + 1;
                        if (current === pageValue) {
                            $("#discussPageSelect").append("<option value='" + pageValue + "' selected>" + pageValue + "</option>");
                        } else {
                            $("#discussPageSelect").append("<option value='" + pageValue + "'>" + pageValue + "</option>");
                        }
                    }

                    //先清空数据
                    for (let i = 1; i <= 5; i++) {
                        $("#discussUsername" + i).empty();
                        $("#discussTime" + i).empty();
                        $("#discussPlace" + i).empty();
                        $("#discussId" + i).empty();
                        $("#discussContent" + i).empty();
                    }
                    //再进行赋值
                    let tucaoDiscussNum;
                    if ((total - size * (current - 1)) >= 5) {
                        tucaoDiscussNum = 5;
                    } else if ((total - size * (current - 1)) < 5) {
                        tucaoDiscussNum = total - size * (current - 1);
                        for (let i = tucaoDiscussNum + 1; i <= 5; i++) {
                            //添加不可见样式
                            $("#discuss" + i).attr("style", "display:none");
                        }
                    }
                    for (let i = 1; i <= tucaoDiscussNum; i++) {
                        //移除不可见样式
                        $("#discuss" + i).removeAttr("style");
                        let userId = JSON.stringify(records[i - 1].userId);
                        let discussId = JSON.stringify(records[i - 1].discussId);
                        let content = JSON.stringify(records[i - 1].content);
                        let place = JSON.stringify(records[i - 1].place);
                        let createTime = JSON.stringify(records[i - 1].createTime);

                        $("#discussTime" + i).html(renderTime(createTime.replace(/\"/g, "")));
                        $("#discussPlace" + i).html(place.replace(/\"/g, ""));
                        $("#discussId" + i).html(discussId.replace(/\"/g, ""));
                        $("#discussContent" + i).html(content.replace(/\"/g, ""));

                        const HtmlId = "discussUsername" + i;
                        getUserByIdAjax(token, userId, HtmlId);
                    }

                }
                //操作失败
                else if (result.code == 500) {
                    spop({
                        template: result.msg,
                        position: 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//根据userId获取用户信息并进行渲染ajax
function getUserByIdAjax(token, userId, HtmlId) {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        headers: {
            "token": token
        },
        url: "http://localhost:2082/user/id?userId=" + userId,
        success: function (data, status, xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const token = xhr.getResponseHeader("token");
            if (token == "overdue") {
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            } else {
                let result = JSON.stringify(data);
                result = eval("(" + result + ")");
                //操作成功
                if (result.code == 200) {
                    const username = eval("(" + JSON.stringify(result.data) + ")").username;
                    $("#" + HtmlId).html(username.replace(/\"/g, ""));
                }
                //操作失败
                else if (result.code == 500) {
                    spop({
                        template: result.msg,
                        position: 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//发布吐槽评论实体类
function AddTucaoDiscuss(userId, tucaoId, content, place, isDelete) {
    this.userId = userId;
    this.tucaoId = tucaoId;
    this.content = content;
    this.place = place;
    this.isDelete = isDelete;
}

//发布评论ajax
function addTucaoDiscussAjax(token, addDiscuss, tucaoId) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        headers: {
            "token": token
        },
        data: JSON.stringify(addDiscuss),
        url: "http://localhost:2082/tucao-discuss",
        success: function (data, status, xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if (responseToken == "overdue") {
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            } else {
                let result = JSON.stringify(data);
                result = eval("(" + result + ")");
                //操作成功
                if (result.code == 200) {
                    //清空textarea中的内容
                    $("#addDiscussContent").val("");
                    spop({
                        template: result.msg,
                        position: 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    //再次进行分页操作
                    const current = $("#discussPageSelect option:selected").text();
                    getPageDiscussByTucaoIdAjax(token, tucaoId, current);
                }
                //操作失败
                else if (result.code == 500) {
                    spop({
                        template: result.msg,
                        position: 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//发布鸡汤评论实体类
function AddHeartDiscuss(userId, heartId, content, place, isDelete) {
    this.userId = userId;
    this.heartId = heartId;
    this.content = content;
    this.place = place;
    this.isDelete = isDelete;
}

//发布鸡汤评论ajax
function addHeartDiscussAjax(token, addDiscuss, heartId) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        headers: {
            "token": token
        },
        data: JSON.stringify(addDiscuss),
        url: "http://localhost:2082/heart-discuss",
        success: function (data, status, xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if (responseToken == "overdue") {
                $('#addTucao').modal('hide');
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            } else {
                let result = JSON.stringify(data);
                result = eval("(" + result + ")");
                //操作成功
                if (result.code == 200) {
                    //清空textarea中的内容
                    $("#addDiscussContent").val("");
                    spop({
                        template: result.msg,
                        position: 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                    //再次进行分页操作
                    const current = $("#discussPageSelect option:selected").text();
                    getPageDiscussByHeartIdAjax(token, heartId, current);
                }
                //操作失败
                else if (result.code == 500) {
                    spop({
                        template: result.msg,
                        position: 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}



